﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Administration;
using PepsiCo.Common;
using T2V.SharePoint.Common.Extensions;
using System.Xml;
using System.Collections.Generic;

namespace PepsiCo.RBS.EventReceivers.BookEventEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class BookEventEventReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// An item is being added.
        /// </summary>
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            SetLocation(properties);
            EnsureUserBookEvent(properties);
            SendEmailAlert(properties);
        }

        /// <summary>
        /// An item is being updated.
        /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);

            if (!PreventAccessOnRecurringItem(properties))
            {
                SetLocation(properties);
                EnsureUserBookEvent(properties);
                SendEmailAlert(properties);
            }
        }

        /// <summary>
        /// An item is being deleted.
        /// </summary>
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            base.ItemDeleting(properties);
            if (!PreventAccessOnRecurringItem(properties))
            {
                SendEmailAlert(properties);
            }
        }

        public void SetLocation(SPItemEventProperties properties)
        {
            try
            {
                string location = string.Empty;

                SPWeb spWeb = properties.Web;

                if (properties.AfterProperties[PepsiCoConstants.BookEvent.MEETING_ROOM_COLUMN] != null && !string.IsNullOrEmpty(properties.AfterProperties[PepsiCoConstants.BookEvent.MEETING_ROOM_COLUMN].ToString()))
                {
                    SPList spListMeetingRoom = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.MeetingRoom.LIST_URL);
                    SPListItem spItemMeetingRoom = spListMeetingRoom.GetItemById(Convert.ToInt32(properties.AfterProperties[PepsiCoConstants.BookEvent.MEETING_ROOM_COLUMN].ToString()));

                    location = spItemMeetingRoom.Title;

                    if (spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.RoomLocation] != null && !string.IsNullOrEmpty(spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.RoomLocation].ToString()))
                    {
                        location += " - " + spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.RoomLocation].ToString();
                    }
                }

                properties.AfterProperties[PepsiCoConstants.BookEvent.LOCATION_COLUMN] = location;
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("BookEventEventReceiver SetLocation", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }
        }

        public void EnsureUserBookEvent(SPItemEventProperties properties)
        {
            try
            {
                SPWeb spWeb = properties.Web;

                if (properties.AfterProperties[PepsiCoConstants.BookEvent.USER_COLUMN] != null && !string.IsNullOrEmpty(properties.AfterProperties[PepsiCoConstants.BookEvent.USER_COLUMN].ToString()))
                {
                    SPUser user = spWeb.EnsureUserByLookupValue(properties.AfterProperties[PepsiCoConstants.BookEvent.USER_COLUMN].ToString());

                    if (properties.AfterProperties[PepsiCoConstants.BookEvent.EMAIL_COLUMN] != null && properties.AfterProperties[PepsiCoConstants.BookEvent.EMAIL_COLUMN].ToString() != user.Email)
                    {
                        properties.AfterProperties[PepsiCoConstants.BookEvent.EMAIL_COLUMN] = user.Email;
                    }
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("BookEventEventReceiver EnsureUserBookEvent", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }
        }

        public void SendEmailAlert(SPItemEventProperties properties)
        {
            try
            {
                SPWeb spWeb = properties.Web;
                //SPList waitingList = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.WaitEvent.LIST_URL);

                if (properties.EventType == SPEventReceiverType.ItemAdding)
                {
                    //Add new
                    SPUser user = spWeb.EnsureUserByLookupValue(properties.AfterProperties[PepsiCoConstants.BookEvent.USER_COLUMN].ToString());

                    SPList spListMeetingRoom = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.MeetingRoom.LIST_URL);
                    SPListItem spItemMeetingRoom = spListMeetingRoom.GetItemById(Convert.ToInt32(properties.AfterProperties[PepsiCoConstants.BookEvent.MEETING_ROOM_COLUMN].ToString()));

                    string availableResources = string.Empty;
                    string[] arrAR = spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.AvailableResources].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 1; i < arrAR.Length; i = i + 2)
                    {
                        availableResources += arrAR[i] + ", ";
                    }
                    availableResources = availableResources.Trim().Trim(',');

                    SPList spListEmailTemplates = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.EmailTemplate.LIST_URL);

                    SPListItem itemEmail = spListEmailTemplates.GetItemById(2); //Email template ID = 2
                    string emailSubject = itemEmail[PepsiCoColumnId.EmailTemplate.EmailSubject].ToString();
                    string emailRawBody = itemEmail[PepsiCoColumnId.EmailTemplate.EmailBody].ToString();

                    string resources = string.Empty;
                    string[] arrR = properties.AfterProperties[PepsiCoConstants.BookEvent.RESOURCE_REQUEST_COLUMN].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 1; i < arrR.Length; i = i + 2)
                    {
                        resources += arrR[i] + ", ";
                    }
                    resources = resources.Trim().Trim(',');

                    DateTime dEventDate = SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties[PepsiCoConstants.BookEvent.EVENT_DATE_COLUMN].ToString());
                    DateTime dEndDate = SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties[PepsiCoConstants.BookEvent.END_DATE_COLUMN].ToString());

                    string recDataText = string.Empty;
                    if (properties.AfterProperties["RecurrenceData"] != null && !string.IsNullOrEmpty(properties.AfterProperties["RecurrenceData"].ToString()))
                    {
                        recDataText = GetRecurrenceDataText(properties.AfterProperties["RecurrenceData"].ToString());
                    }

                    string startTime = string.Empty;
                    string endTime = string.Empty;
                    string recurrenceData = string.Empty;

                    if (!string.IsNullOrEmpty(recDataText))
                    {
                        startTime = dEventDate.ToString("hh:mm tt");
                        endTime = dEndDate.ToString("hh:mm tt");
                        recurrenceData = string.Format("\r\n<br />Start date: {0} - End date: {1}", dEventDate.ToString("MMMM dd yyyy"), dEndDate.ToString("MMMM dd yyyy"))
                                         + "\r\n<br />Recurrence: " + recDataText;
                    }
                    else
                    {
                        startTime = dEventDate.ToString("MMMM dd yyyy hh:mm tt");
                        endTime = dEndDate.ToString("MMMM dd yyyy hh:mm tt");
                    }

                    string emailResolvedBody = string.Format(emailRawBody
                        , user.Name
                        , spItemMeetingRoom.Title
                        , properties.AfterProperties[PepsiCoConstants.BookEvent.TITLE_COLUMN].ToString() //Subject
                        , startTime
                        , endTime + recurrenceData
                        , availableResources
                        , resources
                        );

                    SPUtility.SendEmail(spWeb, true, false, user.Email, emailSubject, emailResolvedBody);
                }
                else if (properties.EventType == SPEventReceiverType.ItemUpdating)
                {
                    //Edit

                    var itemBookEvent = properties.ListItem;
                    SPUser newUser = spWeb.EnsureUserByLookupValue(properties.AfterProperties[PepsiCoConstants.BookEvent.USER_COLUMN].ToString());
                    SPUser oldUser = spWeb.EnsureUserByLookupValue(itemBookEvent[PepsiCoColumnId.BookEvent.User].ToString());

                    if (newUser.ID == oldUser.ID)
                    {
                        if (properties.AfterProperties[PepsiCoConstants.BookEvent.TITLE_COLUMN].ToString().StartsWith("Deleted:") == true)
                        {
                            //delete an instance in recurring event
                            SPList spListMeetingRoom = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.MeetingRoom.LIST_URL);
                            SPListItem spItemMeetingRoom = spListMeetingRoom.GetItemById(Convert.ToInt32(properties.AfterProperties[PepsiCoConstants.BookEvent.MEETING_ROOM_COLUMN].ToString()));

                            string availableResources = string.Empty;
                            string[] arrAR = spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.AvailableResources].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                            for (int i = 1; i < arrAR.Length; i = i + 2)
                            {
                                availableResources += arrAR[i] + ", ";
                            }
                            availableResources = availableResources.Trim().Trim(',');

                            SPList spListEmailTemplates = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.EmailTemplate.LIST_URL);

                            SPListItem itemEmail = spListEmailTemplates.GetItemById(4); //Email template ID = 4
                            string emailSubject = itemEmail[PepsiCoColumnId.EmailTemplate.EmailSubject].ToString();
                            string emailRawBody = itemEmail[PepsiCoColumnId.EmailTemplate.EmailBody].ToString();

                            string resources = string.Empty;
                            string[] arrR = properties.AfterProperties[PepsiCoConstants.BookEvent.RESOURCE_REQUEST_COLUMN].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                            for (int i = 1; i < arrR.Length; i = i + 2)
                            {
                                resources += arrR[i] + ", ";
                            }
                            resources = resources.Trim().Trim(',');

                            DateTime dEventDate = SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties[PepsiCoConstants.BookEvent.EVENT_DATE_COLUMN].ToString());
                            DateTime dEndDate = SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties[PepsiCoConstants.BookEvent.END_DATE_COLUMN].ToString());

                            string startTime = string.Empty;
                            string endTime = string.Empty;

                            startTime = dEventDate.ToString("MMMM dd yyyy hh:mm tt");
                            endTime = dEndDate.ToString("MMMM dd yyyy hh:mm tt");

                            string emailResolvedBody = string.Format(emailRawBody
                                , newUser.Name
                                , spItemMeetingRoom.Title
                                , properties.AfterProperties[PepsiCoConstants.BookEvent.TITLE_COLUMN].ToString() //Subject
                                , startTime
                                , endTime
                                , availableResources
                                , resources
                                );

                            SPUtility.SendEmail(spWeb, true, false, newUser.Email, emailSubject, emailResolvedBody);
                        }
                        else
                        {
                            //same user => send email changed
                            SPList spListMeetingRoom = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.MeetingRoom.LIST_URL);
                            SPListItem spItemMeetingRoom = spListMeetingRoom.GetItemById(Convert.ToInt32(properties.AfterProperties[PepsiCoConstants.BookEvent.MEETING_ROOM_COLUMN].ToString()));

                            string availableResources = string.Empty;
                            string[] arrAR = spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.AvailableResources].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                            for (int i = 1; i < arrAR.Length; i = i + 2)
                            {
                                availableResources += arrAR[i] + ", ";
                            }
                            availableResources = availableResources.Trim().Trim(',');

                            SPList spListEmailTemplates = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.EmailTemplate.LIST_URL);

                            SPListItem itemEmail = spListEmailTemplates.GetItemById(3); //Email template ID = 3
                            string emailSubject = itemEmail[PepsiCoColumnId.EmailTemplate.EmailSubject].ToString();
                            string emailRawBody = itemEmail[PepsiCoColumnId.EmailTemplate.EmailBody].ToString();

                            string resources = string.Empty;
                            string[] arrR = properties.AfterProperties[PepsiCoConstants.BookEvent.RESOURCE_REQUEST_COLUMN].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                            for (int i = 1; i < arrR.Length; i = i + 2)
                            {
                                resources += arrR[i] + ", ";
                            }
                            resources = resources.Trim().Trim(',');

                            DateTime dEventDate = SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties[PepsiCoConstants.BookEvent.EVENT_DATE_COLUMN].ToString());
                            DateTime dEndDate = SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties[PepsiCoConstants.BookEvent.END_DATE_COLUMN].ToString());

                            string recDataText = string.Empty;
                            if (properties.AfterProperties["RecurrenceData"] != null && !string.IsNullOrEmpty(properties.AfterProperties["RecurrenceData"].ToString()))
                            {
                                recDataText = GetRecurrenceDataText(properties.AfterProperties["RecurrenceData"].ToString());
                            }

                            string startTime = string.Empty;
                            string endTime = string.Empty;
                            string recurrenceData = string.Empty;

                            if (!string.IsNullOrEmpty(recDataText))
                            {
                                startTime = dEventDate.ToString("hh:mm tt");
                                endTime = dEndDate.ToString("hh:mm tt");
                                recurrenceData = string.Format("\r\n<br />Start date: {0} - End date: {1}", dEventDate.ToString("MMMM dd yyyy"), dEndDate.ToString("MMMM dd yyyy"))
                                                    + "\r\n<br />Recurrence: " + recDataText;
                            }
                            else
                            {
                                startTime = dEventDate.ToString("MMMM dd yyyy hh:mm tt");
                                endTime = dEndDate.ToString("MMMM dd yyyy hh:mm tt");
                            }

                            string emailResolvedBody = string.Format(emailRawBody
                                , newUser.Name
                                , spItemMeetingRoom.Title
                                , properties.AfterProperties[PepsiCoConstants.BookEvent.TITLE_COLUMN].ToString() //Subject
                                , startTime
                                , endTime + recurrenceData
                                , availableResources
                                , resources
                                );

                            SPUtility.SendEmail(spWeb, true, false, newUser.Email, emailSubject, emailResolvedBody);
                        }
                    }
                    else
                    {
                        //different users, send email new and delete
                        SPList spListMeetingRoom = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.MeetingRoom.LIST_URL);
                        SPListItem spItemMeetingRoom_New = spListMeetingRoom.GetItemById(Convert.ToInt32(properties.AfterProperties[PepsiCoConstants.BookEvent.MEETING_ROOM_COLUMN].ToString()));

                        string availableResources_New = string.Empty;
                        string[] arrAR_New = spItemMeetingRoom_New[PepsiCoColumnId.MeetingRoom.AvailableResources].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 1; i < arrAR_New.Length; i = i + 2)
                        {
                            availableResources_New += arrAR_New[i] + ", ";
                        }
                        availableResources_New = availableResources_New.Trim().Trim(',');

                        SPList spListEmailTemplates = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.EmailTemplate.LIST_URL);

                        SPListItem itemEmail_New = spListEmailTemplates.GetItemById(2); //Email template ID = 2
                        string emailSubject_New = itemEmail_New[PepsiCoColumnId.EmailTemplate.EmailSubject].ToString();
                        string emailRawBody_New = itemEmail_New[PepsiCoColumnId.EmailTemplate.EmailBody].ToString();

                        string resources_New = string.Empty;
                        string[] arrR_New = properties.AfterProperties[PepsiCoConstants.BookEvent.RESOURCE_REQUEST_COLUMN].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 1; i < arrR_New.Length; i = i + 2)
                        {
                            resources_New += arrR_New[i] + ", ";
                        }
                        resources_New = resources_New.Trim().Trim(',');

                        DateTime dEventDate_New = SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties[PepsiCoConstants.BookEvent.EVENT_DATE_COLUMN].ToString());
                        DateTime dEndDate_New = SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties[PepsiCoConstants.BookEvent.END_DATE_COLUMN].ToString());

                        string recDataText = string.Empty;
                        if (properties.AfterProperties["RecurrenceData"] != null && !string.IsNullOrEmpty(properties.AfterProperties["RecurrenceData"].ToString()))
                        {
                            recDataText = GetRecurrenceDataText(properties.AfterProperties["RecurrenceData"].ToString());
                        }

                        string startTime_New = string.Empty;
                        string endTime_New = string.Empty;
                        string recurrenceData_New = string.Empty;

                        if (!string.IsNullOrEmpty(recDataText))
                        {
                            startTime_New = dEventDate_New.ToString("hh:mm tt");
                            endTime_New = dEndDate_New.ToString("hh:mm tt");
                            recurrenceData_New = string.Format("\r\n<br />Start date: {0} - End date: {1}", dEventDate_New.ToString("MMMM dd yyyy"), dEndDate_New.ToString("MMMM dd yyyy"))
                                                + "\r\n<br />Recurrence: " + recDataText;
                        }
                        else
                        {
                            startTime_New = dEventDate_New.ToString("MMMM dd yyyy hh:mm tt");
                            endTime_New = dEndDate_New.ToString("MMMM dd yyyy hh:mm tt");
                        }

                        string emailResolvedBody_New = string.Format(emailRawBody_New
                            , newUser.Name
                            , spItemMeetingRoom_New.Title
                            , properties.AfterProperties[PepsiCoConstants.BookEvent.TITLE_COLUMN].ToString() //Subject
                            , startTime_New
                            , endTime_New + recurrenceData_New
                            , availableResources_New
                            , resources_New
                            );

                        SPUtility.SendEmail(spWeb, true, false, newUser.Email, emailSubject_New, emailResolvedBody_New);

                        ///////////////////////

                        SPListItem spItemMeetingRoom_Old = spListMeetingRoom.GetItemById(Convert.ToInt32(itemBookEvent[PepsiCoColumnId.BookEvent.MeetingRoom].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries)[0]));
                        string availableResources_Old = string.Empty;
                        string[] arrAR_Old = spItemMeetingRoom_Old[PepsiCoColumnId.MeetingRoom.AvailableResources].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 1; i < arrAR_Old.Length; i = i + 2)
                        {
                            availableResources_Old += arrAR_Old[i] + ", ";
                        }
                        availableResources_Old = availableResources_Old.Trim().Trim(',');

                        SPListItem itemEmail_Old = spListEmailTemplates.GetItemById(4); //Email template ID = 4
                        string emailSubject_Old = itemEmail_Old[PepsiCoColumnId.EmailTemplate.EmailSubject].ToString();
                        string emailRawBody_Old = itemEmail_Old[PepsiCoColumnId.EmailTemplate.EmailBody].ToString();

                        string resources_Old = string.Empty;
                        string[] arrR_Old = itemBookEvent[PepsiCoColumnId.BookEvent.ResourceRequest].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 1; i < arrR_Old.Length; i = i + 2)
                        {
                            resources_Old += arrR_Old[i] + ", ";
                        }
                        resources_Old = resources_Old.Trim().Trim(',');

                        string recDataText_Old = string.Empty;
                        if (itemBookEvent["RecurrenceData"] != null && !string.IsNullOrEmpty(itemBookEvent["RecurrenceData"].ToString()))
                        {
                            recDataText_Old = GetRecurrenceDataText(itemBookEvent["RecurrenceData"].ToString());
                        }

                        string startTime_Old = string.Empty;
                        string endTime_Old = string.Empty;
                        string recurrenceData_Old = string.Empty;

                        if (!string.IsNullOrEmpty(recDataText))
                        {
                            startTime_Old = Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.StartDate]).ToString("hh:mm tt");
                            endTime_Old = Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.EndDate]).ToString("hh:mm tt");
                            recurrenceData_Old = string.Format("\r\n<br />Start date: {0} - End date: {1}", Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.StartDate]).ToString("MMMM dd yyyy"), Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.EndDate]).ToString("MMMM dd yyyy"))
                                                + "\r\n<br />Recurrence: " + recDataText_Old;
                        }
                        else
                        {
                            startTime_Old = Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.StartDate]).ToString("MMMM dd yyyy hh:mm tt");
                            endTime_Old = Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.EndDate]).ToString("MMMM dd yyyy hh:mm tt");
                        }

                        string emailResolvedBody_Old = string.Format(emailRawBody_Old
                            , oldUser.Name
                            , spItemMeetingRoom_Old.Title
                            , itemBookEvent.Title //Subject
                            , startTime_Old
                            , endTime_Old + recurrenceData_Old
                            , availableResources_Old
                            , resources_Old
                            );

                        SPUtility.SendEmail(spWeb, true, false, oldUser.Email, emailSubject_Old, emailResolvedBody_Old);
                    }
                    

                }
                else if (properties.EventType == SPEventReceiverType.ItemDeleting)
                {
                    //Delete
                    var itemBookEvent = properties.ListItem;

                    SPUser user = spWeb.EnsureUserByLookupValue(itemBookEvent[PepsiCoColumnId.BookEvent.User].ToString());

                    SPList spListMeetingRoom = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.MeetingRoom.LIST_URL);
                    SPListItem spItemMeetingRoom = spListMeetingRoom.GetItemById(Convert.ToInt32(itemBookEvent[PepsiCoColumnId.BookEvent.MeetingRoom].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries)[0]));
                    string availableResources = string.Empty;
                    string[] arrAR = spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.AvailableResources].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 1; i < arrAR.Length; i = i + 2)
                    {
                        availableResources += arrAR[i] + ", ";
                    }
                    availableResources = availableResources.Trim().Trim(',');

                    SPList spListEmailTemplates = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.EmailTemplate.LIST_URL);

                    SPListItem itemEmail = spListEmailTemplates.GetItemById(4); //Email template ID = 4
                    string emailSubject = itemEmail[PepsiCoColumnId.EmailTemplate.EmailSubject].ToString();
                    string emailRawBody = itemEmail[PepsiCoColumnId.EmailTemplate.EmailBody].ToString();

                    string resources = string.Empty;
                    string[] arrR = itemBookEvent[PepsiCoColumnId.BookEvent.ResourceRequest].ToString().Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 1; i < arrR.Length; i = i + 2)
                    {
                        resources += arrR[i] + ", ";
                    }
                    resources = resources.Trim().Trim(',');

                    string recDataText = string.Empty;
                    if (itemBookEvent["RecurrenceData"] != null && !string.IsNullOrEmpty(itemBookEvent["RecurrenceData"].ToString()))
                    {
                        recDataText = GetRecurrenceDataText(itemBookEvent["RecurrenceData"].ToString());
                    }

                    string startTime = string.Empty;
                    string endTime = string.Empty;
                    string recurrenceData = string.Empty;

                    if (!string.IsNullOrEmpty(recDataText))
                    {
                        startTime = Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.StartDate]).ToString("hh:mm tt");
                        endTime = Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.EndDate]).ToString("hh:mm tt");
                        recurrenceData = string.Format("\r\n<br />Start date: {0} - End date: {1}", Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.StartDate]).ToString("MMMM dd yyyy"), Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.EndDate]).ToString("MMMM dd yyyy"))
                                         + "\r\n<br />Recurrence: " + recDataText;
                    }
                    else
                    {
                        startTime = Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.StartDate]).ToString("MMMM dd yyyy hh:mm tt");
                        endTime = Convert.ToDateTime(itemBookEvent[SPBuiltInFieldId.EndDate]).ToString("MMMM dd yyyy hh:mm tt");
                    }

                    string emailResolvedBody = string.Format(emailRawBody
                        , user.Name
                        , spItemMeetingRoom.Title
                        , itemBookEvent.Title //Subject
                        , startTime
                        , endTime + recurrenceData
                        , availableResources
                        , resources
                        );

                    SPUtility.SendEmail(spWeb, true, false, user.Email, emailSubject, emailResolvedBody);
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("BookEventEventReceiver SendEmailAlert", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }

            
        }

        public string GetRecurrenceDataText(string recurrenceData)
        {
            string result = string.Empty;

            XmlDocument recDataXML = new XmlDocument();
            recDataXML.LoadXml(recurrenceData);

            if (recDataXML.GetElementsByTagName("weekly").Count == 1)
            {
                string templateText = "Every {0} week(s) on:";

                XmlNodeList repeatingTypeList = recDataXML.GetElementsByTagName("weekly");
                XmlNode repeatingType = repeatingTypeList[0];

                string weekFrequency = repeatingType.Attributes["weekFrequency"].Value;
                result = string.Format(templateText, weekFrequency);

                if (repeatingType.Attributes["mo"] != null && repeatingType.Attributes["mo"].Value == "TRUE")
                {
                    result += " Monday,";
                }
                if (repeatingType.Attributes["tu"] != null && repeatingType.Attributes["tu"].Value == "TRUE")
                {
                    result += " Tuesday,";
                }
                if (repeatingType.Attributes["we"] != null && repeatingType.Attributes["we"].Value == "TRUE")
                {
                    result += " Wednesday,";
                }
                if (repeatingType.Attributes["th"] != null && repeatingType.Attributes["th"].Value == "TRUE")
                {
                    result += " Thursday,";
                }
                if (repeatingType.Attributes["fr"] != null && repeatingType.Attributes["fr"].Value == "TRUE")
                {
                    result += " Friday,";
                }
                if (repeatingType.Attributes["sa"] != null && repeatingType.Attributes["sa"].Value == "TRUE")
                {
                    result += " Saturday,";
                }
                if (repeatingType.Attributes["su"] != null && repeatingType.Attributes["su"].Value == "TRUE")
                {
                    result += " Sunday,";
                }

                result = result.TrimEnd(',');
            }
            else if (recDataXML.GetElementsByTagName("monthly").Count == 1)
            {
                string templateText = "Every {0} month(s) on day ";
                XmlNodeList repeatingTypeList = recDataXML.GetElementsByTagName("monthly");
                XmlNode repeatingType = repeatingTypeList[0];

                string monthFrequency = repeatingType.Attributes["monthFrequency"].Value;
                result = string.Format(templateText, monthFrequency);

                string day = repeatingType.Attributes["day"].Value;
                result += day;
            }
            else if (recDataXML.GetElementsByTagName("monthlyByDay").Count == 1)
            {
                string templateText = "Every {0} month(s) on the ";
                XmlNodeList repeatingTypeList = recDataXML.GetElementsByTagName("monthlyByDay");
                XmlNode repeatingType = repeatingTypeList[0];

                string monthFrequency = repeatingType.Attributes["monthFrequency"].Value;
                result = string.Format(templateText, monthFrequency);

                string weekdayOfMonth = repeatingType.Attributes["weekdayOfMonth"].Value;
                result += weekdayOfMonth;

                if (repeatingType.Attributes["mo"] != null && repeatingType.Attributes["mo"].Value == "TRUE")
                {
                    result += " Monday";
                }
                else if (repeatingType.Attributes["tu"] != null && repeatingType.Attributes["tu"].Value == "TRUE")
                {
                    result += " Tuesday";
                }
                else if (repeatingType.Attributes["we"] != null && repeatingType.Attributes["we"].Value == "TRUE")
                {
                    result += " Wednesday";
                }
                else if (repeatingType.Attributes["th"] != null && repeatingType.Attributes["th"].Value == "TRUE")
                {
                    result += " Thursday";
                }
                else if (repeatingType.Attributes["fr"] != null && repeatingType.Attributes["fr"].Value == "TRUE")
                {
                    result += " Friday";
                }
                else if (repeatingType.Attributes["sa"] != null && repeatingType.Attributes["sa"].Value == "TRUE")
                {
                    result += " Saturday";
                }
                else if (repeatingType.Attributes["su"] != null && repeatingType.Attributes["su"].Value == "TRUE")
                {
                    result += " Sunday";
                }
                else if (repeatingType.Attributes["day"] != null && repeatingType.Attributes["day"].Value == "TRUE")
                {
                    result += " day";
                }
                else if (repeatingType.Attributes["weekday"] != null && repeatingType.Attributes["weekday"].Value == "TRUE")
                {
                    result += " weekday";
                }
                else if (repeatingType.Attributes["weekend_day"] != null && repeatingType.Attributes["weekend_day"].Value == "TRUE")
                {
                    result += " weekend day";
                }
            }

            return result;
        }

        public bool PreventAccessOnRecurringItem(SPItemEventProperties properties)
        {
            bool result = false;

            try
            {
                SPWeb spWeb = properties.Web;

                var listBookEvent = properties.List;
                var itemBookEvent = properties.ListItem;

                if (listBookEvent.WriteSecurity == 2 && !spWeb.DoesUserHavePermissions(SPBasePermissions.FullMask))
                {
                    var authorUser = spWeb.EnsureSPFieldUserValueByLookupValue(itemBookEvent[SPBuiltInFieldId.Author].ToString());

                    if (authorUser.User.LoginName != properties.UserLoginName)
                    {
                        result = true;

                        properties.ErrorMessage = "Access Denied";
                        properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
                        properties.RedirectUrl = "_layouts/AccessDenied.aspx";
                        properties.Cancel = true;
                    }
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("BookEventEventReceiver PreventAccessOnRecurringItem", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }

            return result;
        }


        /// <summary>
        /// An item was added
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);

            if (properties.ListItem[PepsiCoConstants.BookEvent.TITLE_COLUMN].ToString().StartsWith("Deleted:") == true)
            {
                CheckAndMoveWaitingListToBookEvent(properties);
            }
        }

        /// <summary>
        /// An item was updated
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            CheckAndMoveWaitingListToBookEvent(properties);
        }

        /// <summary>
        /// An item was deleted
        /// </summary>
        public override void ItemDeleted(SPItemEventProperties properties)
        {
            base.ItemDeleted(properties);
            CheckAndMoveWaitingListToBookEvent(properties);
        }

        public void CheckAndMoveWaitingListToBookEvent(SPItemEventProperties properties)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite spSite = new SPSite(properties.SiteId))
                    {
                        using (SPWeb spWeb = spSite.OpenWeb(properties.Web.ID))
                        {
                            spWeb.AllowUnsafeUpdates = true;

                            SPList waitingList = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.WaitEvent.LIST_URL);

                            if (waitingList != null)
                            {
                                SPList bookEventList = spWeb.Lists[properties.ListId];

                                //DateTime firstDayInMonth = startTime.FirstDayOfMonthFromDateTime();

                                SPQuery queryWaitingList = new SPQuery();
                                queryWaitingList.ExpandRecurrence = true;
                                queryWaitingList.CalendarDate = DateTime.Now;
                                queryWaitingList.Query = string.Format(@"<Where>
                                                                <And>
                                                                    <Geq>
                                                                        <FieldRef Name='EventDate' />
                                                                        <Value Type='DateTime' IncludeTimeValue='TRUE'>
                                                                            <Today />
                                                                        </Value>
                                                                    </Geq>
                                                                    <DateRangesOverlap>
                                                                        <FieldRef Name='EventDate' />
                                                                        <FieldRef Name='EndDate' />
                                                                        <FieldRef Name='RecurrenceID' />
                                                                        <Value Type='DateTime' IncludeTimeValue='TRUE'><Year /></Value>
                                                                    </DateRangesOverlap>
                                                                </And>
                                                            </Where>
                                                            <OrderBy><FieldRef Name='Created' /></OrderBy>");

                                SPListItemCollection waitItems = waitingList.GetItems(queryWaitingList);

                                List<int> listAllowRecurWaitIDs = new List<int>(); //tan dung vong lap cua waitItems de xac dinh chuyen Recur Wait sang Book Events
                                List<int> listIgnoreRecurWaitIDs = new List<int>(); // danh sach bo qua Recur Wait do da xay ra trong qua khu

                                if (waitItems != null && waitItems.Count > 0)
                                {
                                    for (int i = 0; i < waitItems.Count; i++)
                                    {
                                        SPListItem waitItem = waitItems[i];

                                        //check if this is Recurrence type
                                        if (waitItem["Recurrence"] != null && Convert.ToBoolean(waitItem["Recurrence"]) == true)
                                        {
                                            //Is Recurrence
                                            #region [Is Recurrence]

                                            //not select recurring event that root event is on the past
                                            if (!listIgnoreRecurWaitIDs.Exists(x => x == waitItem.ID))
                                            {

                                                //check and set Allow + Ignore lists
                                                if (!listAllowRecurWaitIDs.Exists(x => x == waitItem.ID))
                                                {
                                                    SPListItem rootRecurWaitItem = waitingList.GetItemById(waitItem.ID);
                                                    DateTime firstStartDate = DateTime.Parse(rootRecurWaitItem["EventDate"].ToString());

                                                    if (firstStartDate >= DateTime.Today)
                                                    {
                                                        listAllowRecurWaitIDs.Add(waitItem.ID);
                                                    }
                                                    else
                                                    {
                                                        listIgnoreRecurWaitIDs.Add(waitItem.ID);
                                                    }
                                                }


                                                //check one more time
                                                if (listAllowRecurWaitIDs.Exists(x => x == waitItem.ID))
                                                {
                                                    DateTime startTime = DateTime.Parse(waitItem["EventDate"].ToString());
                                                    DateTime endTime = DateTime.Parse(waitItem["EndDate"].ToString());
                                                    int roomId = new SPFieldLookupValue(waitItem[PepsiCoColumnId.WaitEvent.MeetingRoom].ToString()).LookupId;

                                                    SPQuery queryBookEvent = new SPQuery();
                                                    queryBookEvent.ExpandRecurrence = true;
                                                    queryBookEvent.CalendarDate = startTime;
                                                    queryBookEvent.Query = string.Format(@"<Where>
                                                                                        <DateRangesOverlap>
                                                                                            <FieldRef Name='EventDate' />
                                                                                            <FieldRef Name='EndDate' />
                                                                                            <FieldRef Name='RecurrenceID' />
                                                                                            <Value Type='DateTime' IncludeTimeValue='TRUE'><Today /></Value>
                                                                                        </DateRangesOverlap>
                                                                                    </Where>
                                                                                    <OrderBy><FieldRef Name='EventDate' /></OrderBy>");

                                                    SPListItemCollection bookItems = bookEventList.GetItems(queryBookEvent);

                                                    if (bookItems != null && bookItems.Count > 0)
                                                    {
                                                        foreach (SPListItem bookItem in bookItems)
                                                        {
                                                            if (CheckOverlap(bookItem, startTime, endTime, roomId))
                                                            {
                                                                listAllowRecurWaitIDs.Remove(waitItem.ID);
                                                                listIgnoreRecurWaitIDs.Add(waitItem.ID);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }

                                            #endregion [Is Recurrence]
                                        }
                                        else
                                        {
                                            //Not Recurrence
                                            #region [Not Recurrence]
                                            DateTime startTime = DateTime.Parse(waitItem["EventDate"].ToString());
                                            DateTime endTime = DateTime.Parse(waitItem["EndDate"].ToString());
                                            int roomId = new SPFieldLookupValue(waitItem[PepsiCoColumnId.WaitEvent.MeetingRoom].ToString()).LookupId;

                                            SPQuery queryBookEvent = new SPQuery();
                                            queryBookEvent.ExpandRecurrence = true;
                                            queryBookEvent.CalendarDate = startTime;
                                            queryBookEvent.Query = string.Format(@"<Where>
                                                                                        <DateRangesOverlap>
                                                                                            <FieldRef Name='EventDate' />
                                                                                            <FieldRef Name='EndDate' />
                                                                                            <FieldRef Name='RecurrenceID' />
                                                                                            <Value Type='DateTime' IncludeTimeValue='TRUE'><Today /></Value>
                                                                                        </DateRangesOverlap>
                                                                                    </Where>
                                                                                    <OrderBy><FieldRef Name='EventDate' /></OrderBy>");

                                            SPListItemCollection bookItems = bookEventList.GetItems(queryBookEvent);

                                            bool moveToBookEvent = true;

                                            if (bookItems != null && bookItems.Count > 0)
                                            {
                                                foreach (SPListItem bookItem in bookItems)
                                                {
                                                    moveToBookEvent = !CheckOverlap(bookItem, startTime, endTime, roomId);

                                                    if (moveToBookEvent == false) break;
                                                }
                                            }


                                            if (moveToBookEvent == true)
                                            {
                                                listAllowRecurWaitIDs.Add(waitItem.ID);
                                            }

                                            #endregion [Not Recurrence]
                                        }
                                    }
                                }

                                //handle recurring Allow Wait List
                                if (listAllowRecurWaitIDs.Count > 0)
                                { 
                                    //recheck overlap in allowed WaitItems with each other
                                    List<int> listValidWaitIDs = new List<int>(); // danh sach WaitID hop le cuoi cung sau khi da check overlap lan nhau 

                                    //the first item will be always valid, so only check the 2nd item till the last item
                                    listValidWaitIDs.Add(listAllowRecurWaitIDs[0]);
                                    for (int i = 1; i < listAllowRecurWaitIDs.Count; i++ )
                                    {
                                        //for items need to check
                                        SPQuery queryCheckWaitItem = new SPQuery();
                                        queryCheckWaitItem.ExpandRecurrence = true;
                                        queryCheckWaitItem.CalendarDate = DateTime.Now;
                                        queryCheckWaitItem.Query = string.Format(@"<Where>
                                                                <And>
                                                                    <Eq>
                                                                        <FieldRef Name='ID' />
                                                                        <Value Type='Counter'>{0}</Value>
                                                                    </Eq>
                                                                    <DateRangesOverlap>
                                                                        <FieldRef Name='EventDate' />
                                                                        <FieldRef Name='EndDate' />
                                                                        <FieldRef Name='RecurrenceID' />
                                                                        <Value Type='DateTime' IncludeTimeValue='TRUE'><Year /></Value>
                                                                    </DateRangesOverlap>
                                                                </And>
                                                            </Where>
                                                            <OrderBy><FieldRef Name='EventDate' /></OrderBy>", listAllowRecurWaitIDs[i]);

                                        SPListItemCollection checkWaitItems = waitingList.GetItems(queryCheckWaitItem);

                                        //for items are already valid
                                        string valueValidWaitIDs = string.Empty;
                                        foreach (int waitID in listValidWaitIDs)
                                        {
                                            valueValidWaitIDs += "<Value Type='Counter'>" + waitID.ToString() + "</Value>";
                                        }
                                        SPQuery queryValidWaitItem = new SPQuery();
                                        queryValidWaitItem.ExpandRecurrence = true;
                                        queryValidWaitItem.CalendarDate = DateTime.Now;
                                        queryValidWaitItem.Query = string.Format(@"<Where>
                                                                <And>
                                                                    <In>
                                                                        <FieldRef Name='ID' />
                                                                        <Values>{0}</Values>
                                                                    </In>
                                                                    <DateRangesOverlap>
                                                                        <FieldRef Name='EventDate' />
                                                                        <FieldRef Name='EndDate' />
                                                                        <FieldRef Name='RecurrenceID' />
                                                                        <Value Type='DateTime' IncludeTimeValue='TRUE'><Year /></Value>
                                                                    </DateRangesOverlap>
                                                                </And>
                                                            </Where>
                                                            <OrderBy><FieldRef Name='EventDate' /></OrderBy>", valueValidWaitIDs);

                                        SPListItemCollection validWaitItems = waitingList.GetItems(queryValidWaitItem);

                                        bool finalCheckIsValid = true;

                                        foreach (SPListItem checkWaitItem in checkWaitItems)
                                        {
                                            DateTime startTime = DateTime.Parse(checkWaitItem["EventDate"].ToString());
                                            DateTime endTime = DateTime.Parse(checkWaitItem["EndDate"].ToString());
                                            int roomId = new SPFieldLookupValue(checkWaitItem[PepsiCoColumnId.WaitEvent.MeetingRoom].ToString()).LookupId;

                                            foreach (SPListItem validWaitItem in validWaitItems)
                                            {
                                                finalCheckIsValid = !CheckOverlapInWaittingList(validWaitItem, startTime, endTime, roomId);

                                                if (finalCheckIsValid == false) break;
                                            }

                                            if (finalCheckIsValid == false) break;
                                        }

                                        if (finalCheckIsValid == true)
                                        {
                                            listValidWaitIDs.Add(listAllowRecurWaitIDs[i]);
                                        }
                                    }



                                    //finally, move allowed Wait Items to Book Events
                                    foreach (int waitID in listValidWaitIDs)
                                    {
                                        var waitItem = waitingList.GetItemById(waitID);

                                        var newItem = bookEventList.AddItem();
                                        newItem["Title"] = waitItem["Title"];
                                        newItem["RecurrenceData"] = waitItem["RecurrenceData"];
                                        newItem["EventType"] = waitItem["EventType"];
                                        newItem["EventDate"] = waitItem["EventDate"];
                                        newItem["EndDate"] = waitItem["EndDate"];
                                        newItem["UID"] = System.Guid.NewGuid();
                                        newItem["TimeZone"] = waitItem["TimeZone"];
                                        newItem["Recurrence"] = waitItem["Recurrence"];
                                        newItem["XMLTZone"] = waitItem["XMLTZone"];

                                        newItem["User"] = waitItem["User"];
                                        newItem["Department"] = waitItem["Department"];
                                        newItem["Email"] = waitItem["Email"];
                                        newItem["PhoneNumber"] = waitItem["PhoneNumber"];
                                        newItem["Location"] = waitItem["Location"];
                                        newItem["MeetingRoom"] = waitItem["MeetingRoom"];
                                        newItem["ResourceRequest"] = waitItem["ResourceRequest"];

                                        newItem["Author"] = waitItem["Author"];
                                        newItem["Created"] = waitItem["Created"];
                                        newItem["Editor"] = waitItem["Editor"];
                                        newItem["Modified"] = waitItem["Modified"];
                                        newItem.Update();

                                        waitItem.Delete();
                                    }
                                }
                            }

                            spWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("BookEventEventReceiver CheckAndMoveWaitingListToBookEvent", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }
        }

        /// <summary>
        /// CheckOverlapInBookEvents
        /// </summary>
        /// <param name="item"></param>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <param name="roomId"></param>
        /// <returns></returns>
        private bool CheckOverlap(SPListItem item, DateTime startDateTime, DateTime endDateTime, int roomId)
        {
            bool timeOverlap = false;

            if (item[PepsiCoColumnId.BookEvent.MeetingRoom] != null && new SPFieldLookupValue(item[PepsiCoColumnId.BookEvent.MeetingRoom].ToString()).LookupId == roomId)
            {
                DateTime eventStartDateTime = DateTime.Parse(item["EventDate"].ToString());

                DateTime eventEndDateTime = DateTime.Parse(item["EndDate"].ToString());

                timeOverlap = false;

                //if newstartdate >= eStartDate and newStartDate < eEndDate
                if (startDateTime >= eventStartDateTime && startDateTime < eventEndDateTime)
                {
                    timeOverlap = true;
                }

                //if newEndDate > eStartDate and newEndDate <= eEndDate
                else if (endDateTime > eventStartDateTime && endDateTime <= eventEndDateTime)
                {
                    timeOverlap = true;
                }

                // if eStartDate >= newStartDate and eStartDate < newEndDate
                else if (eventStartDateTime >= startDateTime && eventStartDateTime < endDateTime)
                {
                    timeOverlap = true;
                }

                // if eEndDate > newStartDate and eEndDate <= newEndDate
                else if (eventEndDateTime > startDateTime && eventEndDateTime <= endDateTime)
                {
                    timeOverlap = true;
                }

                // if newStartDate = eStartDate and newEndDate = eEndDate
                else if (startDateTime == eventStartDateTime && endDateTime == eventEndDateTime)
                {
                    timeOverlap = true;
                }
            }

            return timeOverlap;
        }

        private bool CheckOverlapInWaittingList(SPListItem item, DateTime startDateTime, DateTime endDateTime, int roomId)
        {
            bool timeOverlap = false;

            if (item[PepsiCoColumnId.WaitEvent.MeetingRoom] != null && new SPFieldLookupValue(item[PepsiCoColumnId.WaitEvent.MeetingRoom].ToString()).LookupId == roomId)
            {
                DateTime eventStartDateTime = DateTime.Parse(item["EventDate"].ToString());

                DateTime eventEndDateTime = DateTime.Parse(item["EndDate"].ToString());

                timeOverlap = false;

                //if newstartdate >= eStartDate and newStartDate < eEndDate
                if (startDateTime >= eventStartDateTime && startDateTime < eventEndDateTime)
                {
                    timeOverlap = true;
                }

                //if newEndDate > eStartDate and newEndDate <= eEndDate
                else if (endDateTime > eventStartDateTime && endDateTime <= eventEndDateTime)
                {
                    timeOverlap = true;
                }

                // if eStartDate >= newStartDate and eStartDate < newEndDate
                else if (eventStartDateTime >= startDateTime && eventStartDateTime < endDateTime)
                {
                    timeOverlap = true;
                }

                // if eEndDate > newStartDate and eEndDate <= newEndDate
                else if (eventEndDateTime > startDateTime && eventEndDateTime <= endDateTime)
                {
                    timeOverlap = true;
                }

                // if newStartDate = eStartDate and newEndDate = eEndDate
                else if (startDateTime == eventStartDateTime && endDateTime == eventEndDateTime)
                {
                    timeOverlap = true;
                }
            }

            return timeOverlap;
        }
    }
}
